package com.information.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import okio.BufferedSource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
public class AIService {
    
    private static final String API_KEY = System.getenv("OPENAI_API_KEY") != null ? 
        System.getenv("OPENAI_API_KEY") : "sk-9qXiW4V1xBbWVgoSin2Me5XU4swyivMSntwyHqXR4eyLJbpo";
    private static final String BASE_URL = "https://api.chatanywhere.tech/v1";
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .callTimeout(60, TimeUnit.SECONDS)
            .build();
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 存储用户会话上下文
    private final Map<String, List<Map<String, String>>> userContexts = new ConcurrentHashMap<>();
    
    public SseEmitter chatStream(String userId, String message) throws IOException {
        SseEmitter emitter = new SseEmitter(60000L);
        
        // 获取或创建用户上下文
        List<Map<String, String>> context = userContexts.computeIfAbsent(userId, k -> new ArrayList<>());
        
        // 添加用户消息到上下文
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", message);
        context.add(userMessage);
        
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "gpt-3.5-turbo");
        requestBody.put("messages", context);
        requestBody.put("stream", true);
        requestBody.put("max_tokens", 1000);
        
        String jsonBody = objectMapper.writeValueAsString(requestBody);
        
        Request request = new Request.Builder()
                .url(BASE_URL + "/chat/completions")
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(jsonBody, MediaType.parse("application/json")))
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            private StringBuilder assistantMessage = new StringBuilder();
            
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    emitter.send(SseEmitter.event()
                            .name("error")
                            .data("AI服务暂时不可用，请稍后重试"));
                    emitter.complete();
                } catch (IOException ex) {
                    emitter.completeWithError(ex);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (BufferedSource source = response.body().source()) {
                    String line;
                    while ((line = source.readUtf8Line()) != null) {

                        if (line.startsWith("data: ")) {
                            String json = line.substring(6);
                            if ("[DONE]".equals(json)) {
                                // 保存助手回复到上下文
                                Map<String, String> aiMessage = new HashMap<>();
                                aiMessage.put("role", "assistant");
                                aiMessage.put("content", assistantMessage.toString());
                                context.add(aiMessage);

                                emitter.send(SseEmitter.event().data("[DONE]"));
                                emitter.complete();
                                break;
                            }

                            try {
                                JsonNode jsonNode = objectMapper.readTree(json);
                                JsonNode choices = jsonNode.path("choices");
                                if (choices.isArray() && choices.size() > 0) {
                                    JsonNode delta = choices.get(0).path("delta");
                                    String content = delta.path("content").asText("");
                                    if (!content.isEmpty()) {
                                        assistantMessage.append(content);
                                        // 确保SSE格式正确
                                        emitter.send(SseEmitter.event().data(content));
                                    }
                                }
                            } catch (Exception e) {
                                System.err.println("解析JSON失败: " + json + ", 错误: " + e.getMessage());
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println("处理响应失败: " + e.getMessage());
                    emitter.send(SseEmitter.event().data("处理响应时出错"));
                    emitter.completeWithError(e);
                }
            }
        });
        
        return emitter;
    }
    
    public void clearContext(String userId) {
        userContexts.remove(userId);
    }
    
    public int getContextSize(String userId) {
        List<Map<String, String>> context = userContexts.get(userId);
        return context != null ? context.size() : 0;
    }
}